package x.ovo.wechat.bot;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import x.ovo.wechat.bot.common.entity.Contact;
import x.ovo.wechat.bot.common.entity.event.MessageEvent;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.event.Event;
import x.ovo.wechat.bot.common.event.EventListener;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j(topic = "历史上的今天")
public class HistoryListener extends EventListener<MessageEvent<TextMessage>> {

    private static final String URL = "https://api.linhun.vip/api/history?format=json&apiKey=67e2897ce084366d94d44815c8561b75";
    private static final Pattern PATTERN = Pattern.compile("\"content\":\\s?\\[((.*\n?)+)]");

    @Override
    public boolean support(Event<?> event) {
        return event instanceof MessageEvent && event.getSource() instanceof TextMessage && ((MessageEvent<?>) event).getContent().equals("历史上的今天");
    }

    @Override
    public void onEvent(MessageEvent<TextMessage> event) {
        Contact fromUser = event.getSource().getFromUser();
        try {
            OkHttpClient client = (OkHttpClient) this.context.getHttpEngine().getRawEngine();
            Request request = new Request.Builder().url(URL).build();
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful() && Objects.nonNull(response.body())) {
                    Matcher matcher = PATTERN.matcher(response.body().string());
                    if (matcher.find()) {
                        String group = matcher.group(1);
                        String[] split = group.split(",");
                        StringBuilder sb = new StringBuilder();
                        for (String s1 : split) {
                            sb.append("\n").append(s1.trim().replaceAll("\"", ""));
                        }
                        this.context.getApi().sendText(fromUser.getUserName(), "历史上的今天：" + sb);
                        return;
                    }
                }
            }
            this.context.getApi().sendText(fromUser.getUserName(), "获取数据失败了");
        } catch (Exception e) {
            log.error("获取历史上的今天失败", e);
            this.context.getApi().sendText(fromUser.getUserName(), "获取数据失败了");
        }
    }
}
